<script setup lang="ts">
import { Table } from "@/models/reactiveComponent";
import { computed, inject, onMounted, ref } from "vue";

import * as injectKeys from "@/services/injectKeys";
import * as tableUtils from "./table";
import Dynamic from "@/components/Dynamic.vue";

const props = defineProps<{ model: Table }>();
const model = props.model;

const tableRef = ref(null);

const columnPropsMap = new Map<string, Record<string, any>>(
  Object.entries(model.columnProps ?? {})
);
function getColumnProps(name: string) {
  if (columnPropsMap.has(name)) {
    return columnPropsMap.get(name)!;
  }

  return {};
}

const reactdataServices = inject(injectKeys.reactdataServicesKey)!;
const actionsService = inject(injectKeys.actionsServiceKey)!;
const componentInfosService = inject(injectKeys.componentInfosServiceKey)!;

const filterUtils = reactdataServices.getFilterUtils(model);

const data = filterUtils.getData();

const tableData = computed(() => data.value.rows);
const columns = computed(() => {
  return data.value.fields.map((c) => ({
    name: c,
    label: c,
    field: c,
    ...getColumnProps(c),
  }));
});

const visibleColumnsRef = ref(columns.value.map((v) => v.name));

const visibleColumns = computed({
  get: () => {
    return visibleColumnsRef.value;
  },
  set: (val) => {
    visibleColumnsRef.value = val ?? [];
  },
});

// infos
componentInfosService.setInfo(model.id, {
  visibleColumns,
  columns,
});

// actions
const { copy } = tableUtils.useCopyData2excel();

function onclickCopyBtn() {
  copy(data);
}

actionsService.register(
  model.id,
  "copy_to_clipboard_by_excel_format",
  onclickCopyBtn
);

onMounted(() => {
  actionsService.register(
    model.id,
    "toggleFullscreen",
    tableRef.value.toggleFullscreen
  );
});
</script>

<template>
  <div class="bi-table" :data-tag="model.tag">
    <q-table
      ref="tableRef"
      :rows="tableData"
      :columns="columns"
      :visible-columns="visibleColumns"
      dense
      v-bind="model.props"
      style="width: 100%; height: 100%"
      :style="model.styles"
    >
      <template v-if="model.topSlot" v-slot:top="props">
        <Dynamic
          :component="cp"
          v-for="cp in model.topSlot"
          :key="cp.id"
        ></Dynamic>
      </template>
    </q-table>
  </div>
</template>

<style scoped lang="less"></style>
